<?php

namespace app;

use think\db\exception\{
    DataNotFoundException,
    ModelNotFoundException
};
use think\exception\{
    Handle,
    HttpException,
    HttpResponseException,
    ValidateException,
};
use think\Response;
use Throwable;
use Exception;

/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        if (!$this->isIgnoreReport($exception)) {
            // 收集异常数据
            $request = $this->app->request;
            $logInfos = [
                'error' => '[' . $exception->getCode() . '] ' . $exception->getMessage(),
                'file' => $exception->getFile() . ':' . $exception->getLine(),
                'url'  => $request->url(),
                'param' => json_encode($request->param(), JSON_UNESCAPED_UNICODE),
            ];

            $log = '';
            foreach ($logInfos as $key => $value) {
                $log .= $key . ': ' . $value . PHP_EOL;
            }

            if ($this->app->config->get('log.record_trace')) {
                $log .= PHP_EOL . $exception->getTraceAsString();
            }

            try {
                $this->app->log->record($log, 'error');
            } catch (Exception $e) {
            }
        }
    }

    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Response
     */
    public function render($request, Throwable $e): Response
    {
        // 添加自定义异常处理机制

        /** 自定义,处理验证异常 */
        if ($e instanceof ValidateException) {
            // 批量验证
            if (is_array($e->getError())) {
                return failed($e->getMessage(), 20, $e->getError());
            } else {
                return failed($e->getMessage(), 10);
            }
        } else if ($e instanceof DataNotFoundException) {
            return failed('数据不存在', 1);
        } else if ($e instanceof ModelNotFoundException) {
            $model = $e->getModel();
            $modelName = property_exists($model, 'modelAlias')
                ? $model::$modelAlias
                : '模型';
            return failed($modelName . '不存在', 1);
        }

        // 其他错误交给系统处理
        return parent::render($request, $e);
    }
}
